const admin = require("../model/adminModel");
const student = require("../model/studentModel");
const dean = require("../model/deanModel");
const teacher = require("../model/teacherModel");

const log4js = require("log4js");
const logger = log4js.getLogger();

const config = require("../config");
const jwt = require("../utils/jwt");

const ResponseMessage = require("../response/message");

const {
  updateStudentLoginStatus,
  updateTeacherLoginStatus,
  updateDeanLoginStatus,
  updateAdminLoginStatus,
} = require("../persistent_api/loginApi");

/**
 * 返回登录成功所需要的数据
 * @param {Request} req
 * @param {Response} res
 */

exports.loginCore = (req, res) => {
  req.body.expire = Date.now() + config.expire;
  if(req.userInfo){
    req.body.id = req.userInfo._id;
  }
  res.send(
    new ResponseMessage(201, "success", {
      userInfo: req.userInfo || {},
      token: jwt.sign(config.header, req.body, config.secret),
    }) 
  ); 
};
/**
 * 登录态认证返回响应信息 核心逻辑在认证中间件中处理
 * @param {Request} req
 * @param {Response} res
 */
exports.loginAuth = (req, res) => {
  res.send(req.responseMessage);
};

exports.logoutCore = async (req, res) => {
  const { id, loginType } = req.query;
  let modifiedCount = 0;
  try{
    if (loginType === "1") modifiedCount = (await updateStudentLoginStatus(null, null, 0, id)).modifiedCount;
    if (loginType === "2") modifiedCount = (await updateTeacherLoginStatus(null, null, 0, id)).modifiedCount;
    if (loginType === "3") modifiedCount = (await updateDeanLoginStatus(null, null, 0, id)).modifiedCount;
    if (loginType === "4") modifiedCount = (await updateAdminLoginStatus(null, null, 0, id)).modifiedCount;
    if (modifiedCount === 0) {
      logger.warn(req.ip + " - " + req.method + " - " + req.originalUrl + " - 登出失败，请确认传递的登录类型正确或者您还未登录")
      return res.send(new ResponseMessage(201,"登出失败，请确认传递的登录类型正确或者您还未登录",{}));
    }
  }catch(error){
    logger.error(req.ip + " - " + req.method + " - " + req.originalUrl + " - 网络错误,登出失败")
    return res.send(new ResponseMessage(500,"网络错误,登出失败",{}));
  }
  logger.error(req.ip + " - " + req.method + " - " + req.originalUrl + " - 登出成功")
  res.send(new ResponseMessage(201,"success",{}));
};
